<template>
  <div class="listContent" ref="mainCon">
    <div class="mainCon">
      <el-row
        class="toolbar searchInputWidth"
        style="padding-bottom: 0; position: relative"
      >
        <el-form :inline="true" :model="filterField" ref="searchConditions">
          <el-col :lg="8" :xl="6">
            <el-form-item label="事项类型" class="row-padding-bottom">
              <el-select
                v-model="filterField.id"
                filterable
                placeholder="请选择"
                clearable
                :popper-append-to-body="false"
              >
                <el-option
                  v-for="(item, index) in eventTypeArr"
                  :key="index"
                  :label="item.name"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :lg="8" :xl="6">
            <el-form-item label="创建日期" class="row-padding-bottom">
              <timeSelection
                @getStartTimeValue="getStartTimeValue"
                @getEndTimeValue="getEndTimeValue"
              ></timeSelection>
            </el-form-item>
          </el-col>

          <!-- <el-form-item>
                        <el-button
                            type="primary"
                            icon="icon iconfont iconchazhao1"
                            @click="searchList"
                            class="commonBtn"
                        ></el-button>
                    </el-form-item> -->
          <el-form-item label="">
            <el-button
              type="primary"
              icon="icon iconfont iconchazhao1"
              @click="searchList"
              class="searchBtn"
            >
              <span>搜索</span>
            </el-button>
            <exportBtn
              v-if="!isShowAdd"
              :dataLen="tableList.length"
              :filterField="filterField"
              :api="api"
            ></exportBtn>
            <!-- <el-button
                            v-show="isShowAdd"
                            type="primary"
                            class="commonBut saveBtn addEvent"
                            @click="addEventType"
                            icon="icon iconfont icontianjia"
                            > <span class="opetareText">新增事项类型</span></el-button> -->
          </el-form-item>
        </el-form>
      </el-row>
      <div class="spacing"></div>
      <div
        ref="tableBox"
        :class="hiddleToolBar ? 'tableBoxCur tableBox' : 'tableBoxCur'"
      >
        <div style="margin-bottom: 24px" v-if="isShowAdd">
          <exportBtn
            :dataLen="tableList.length"
            :filterField="filterField"
            :api="api"
          ></exportBtn>
          <el-button
            type="primary"
            class="commonBut saveBtn addEvent"
            @click="addEventType"
            icon="icon iconfont icontianjia"
          >
            <span class="opetareText">新增事项类型</span>
          </el-button>
        </div>
        <el-table
          ref="tableBox1"
          :max-height="tableHeight"
          :data="tableList"
          @sort-change="sortChange"
          v-loading="loading"
          :header-cell-style="{ background: '#eef1f6', color: '#606266' }"
          highlight-current-row
          stripe
          style="border: 1px solid #dfe6ec"
        >
          <el-table-column
            label="序号"
            type="index"
            width="80"
            align="center"
          ></el-table-column>
          <el-table-column
            prop="name"
            label="事项类型"
            align="left"
            min-width="20%"
          ></el-table-column>
          <el-table-column
            prop="num"
            label="事项数量"
            align="center"
            :formatter="formatTd"
            min-width="20%"
          ></el-table-column>
          <el-table-column
            prop="createTime"
            label="创建日期"
            align="center"
            :formatter="formatTd"
            sortable="custom"
            min-width="20%"
          ></el-table-column>
          <el-table-column label="操作" :formatter="formatTd" width="130">
            <template slot-scope="scope">
              <el-link
                type="primary"
                v-if="isShowUpdate"
                @click="updateEvent(scope.row)"
                >修改</el-link
              >
              <el-link
                type="primary"
                v-if="isShowDelete"
                @click="deleteEvent(scope.row)"
                >删除</el-link
              >
              <span v-if="!isShowUpdate && !isShowDelete">--</span>
            </template>
          </el-table-column>
          <!-- 表格数据为空时，页面显示 -->
          <div slot="empty" v-show="isShow">
            <emptyTable emptyText="暂无相关数据"></emptyTable>
          </div>
        </el-table>
        <!-- getTableList为获取子组件的数据 -->
        <Pagination
          ref="pagination"
          @getList="getTableList"
          :filterField="filterField"
          :requestUrl="requestUrl"
          @getpageNo="getpageNo"
          @getpageSize="getpageSize"
        ></Pagination>
      </div>
    </div>
    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      @close="closeDialog"
      custom-class="dialog-minwidth"
      width="420px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :modal-append-to-body="false"
      class="tipDialog"
    >
      <el-form
        :model="ruleForm"
        ref="ruleForm"
        label-width="120px"
        class="demo-ruleForm"
      >
        <el-form-item label="事项类型">
          <el-input
            type="text"
            maxlength="15"
            show-word-limit
            placeholder="请输入事项类型名称"
            clearable
            v-model="ruleForm.eventTypeDesc"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="closeDialog" class="cancel">取 消</el-button>
        <el-button
          v-sdc
          type="primary"
          class="save"
          @click.native="saveEventType(actionType)"
          :loading="isAdd"
          >确 定</el-button
        >
      </div>
    </el-dialog>
    <el-dialog
      title="提示"
      :visible.sync="delDialogVisible"
      width="30%"
      center
      :close-on-press-escape="false"
      :close-on-click-modal="false"
    >
      <span>请确认是否删除该条信息？</span>
      <span slot="footer" class="dialog-footer">
        <el-button class="btn cancel" @click="delDialogVisible = false"
          >取 消</el-button
        >
        <el-button type="primary" class="btn save" @click="delEventType()"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
import emptyTable from '@/components/publicCom/emptyTable'
import Pagination from '@/components/publicCom/pagination'

export default {
  name: 'EventTypeList',
  components: {
    emptyTable,
    Pagination,
  },
  data() {
    return {
      dialogTitle: '新增事项类型',
      dialogVisible: false,
      isAdd: false,
      ruleForm: {
        eventTypeDesc: '',
      },
      actionType: 'add',
      delDialogVisible: false,
      eventTypeId: '',
      eventTypeArr: [],
      selectLevel: [],
      //表格数据
      tableList: [],
      requestUrl: '/api-gov/ipqcType/base/findTypes',
      //搜索条件
      filterField: {
        id: '',
        startDate: '',
        endDate: '',
      },
      pageSize: 20,
      pageNo: 1,
      isShow: false, //列表加载
      loading: false,
      isShowAdd: false,
      isShowUpdate: false,
      isShowDelete: false,
      hiddleToolBar: false,
      tableHeight: null,
      api: '',
    }
  },
  created() {
    this.getEventType()
    this.$nextTick(function () {
      this.$refs.pagination.getTableListData()
    })
    this.getApi()
    this.isShowAdd =
      this.$store.state.buttonLimitsArr.indexOf('patrolConfig:add') > -1
    this.isShowUpdate =
      this.$store.state.buttonLimitsArr.indexOf('patrolConfig:update') > -1
    this.isShowDelete =
      this.$store.state.buttonLimitsArr.indexOf('patrolConfig:delete') > -1
  },
  activated() {
    this.getEventType()
    window.addEventListener('scroll', this.handleScroll, true)
    this.$nextTick(function () {
      this.$refs.pagination.getTableListData(this.pageNo, this.pageSize)
      this.$refs.tableBox1.doLayout()
    })
  },
  deactivated() {
    let that = this
    window.removeEventListener('scroll', that.handleScroll, true)
  },
  beforeDestroy() {
    let that = this
    window.removeEventListener('scroll', that.handleScroll, true)
  },
  methods: {
    getpageSize(val) {
      this.pageSize = val
    },
    getpageNo(val) {
      this.pageNo = val
    },
    getStartTimeValue(val) {
      if (val) {
        this.filterField.startDate = val
      } else {
        this.filterField.startDate = ''
      }
    },
    getEndTimeValue(val) {
      if (val) {
        this.filterField.endDate = val
      } else {
        this.filterField.endDate = ''
      }
    },
    // 新增事项
    addEventType() {
      this.actionType = 'add'
      this.dialogTitle = '新增事项类型'
      this.dialogVisible = true
    },
    closeDialog() {
      this.dialogVisible = false
      this.ruleForm.eventTypeDesc = ''
    },
    // 修改事项
    updateEvent(row) {
      this.actionType = 'update'
      this.dialogTitle = '修改事项类型'
      this.eventTypeId = row.id
      this.ruleForm.eventTypeDesc = row.name
      this.dialogVisible = true
    },
    // 删除事项
    deleteEvent(row) {
      // this.delDialogVisible = true;
      this.eventTypeId = row.id
      this.$confirm('确认删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          this.delEventType()
        })
        .catch(() => {
          // this.$message({
          //   type: 'info',
          //   message: '已取消删除'
          // });
        })
    },
    delEventType() {
      return this.axios({
        method: 'post',
        url: 'api-gov/ipqcType/base/deleteType',
        data: {
          typeId: this.eventTypeId,
        },
      })
        .then((response) => {
          if (!response.data.hasError) {
            this.$message.success('删除成功')
            this.delDialogVisible = false
            this.getEventType()
            this.$nextTick(function () {
              this.$refs.pagination.getTableListData(this.pageNo, this.pageSize)
            })
          } else {
            this.$message.error(response.data.errorMsg)
          }
        })
        .catch((error) => {
          if (error.response) {
            this.$message.error(error.response.data)
          }
        })
    },
    // 保存事项类型
    saveEventType() {
      this.isAdd = true
      if (this.ruleForm.eventTypeDesc || this.ruleForm.eventTypeDesc === '0') {
        let data = {
          name: this.ruleForm.eventTypeDesc,
        }
        let url = 'api-gov/ipqcType/base/addType'
        if (this.actionType === 'update') {
          Object.assign(data, { id: this.eventTypeId })
          url = 'api-gov/ipqcType/base/modifyType'
        }
        return this.axios({
          method: 'post',
          url,
          data,
        })
          .then((response) => {
            if (!response.data.hasError) {
              this.$message.success('操作成功')
              this.isAdd = false
              this.dialogVisible = false
              this.getEventType()
              this.$nextTick(function () {
                this.$refs.pagination.getTableListData(
                  this.pageNo,
                  this.pageSize
                )
              })
            } else {
              this.isAdd = false
              this.$message.error(response.data.errorMsg)
            }
          })
          .catch((error) => {
            if (error.response) {
              this.$message.error(error.response.data)
            }
          })
      } else {
        this.isAdd = false
        this.$message.error('请输入事项类型名称')
      }
    },
    // 获取事项类别
    getEventType() {
      return this.axios({
        method: 'get',
        url: 'api-gov/ipqcType/base/findAllTypes',
      })
        .then((response) => {
          if (!response.data.hasError) {
            const results = response.data.result
            this.eventTypeArr = results
          } else {
            this.$message.error(response.data.errorMsg)
          }
        })
        .catch((error) => {
          if (error.response) {
            this.$message.error(error.response.data)
          }
        })
    },
    getTableList(data) {
      this.tableList = data
      this.loading = false
      if (this.tableList.length < 1) {
        this.isShow = true
      }
    },
    // 搜索
    searchList() {
      this.$refs.pagination.getTableListData()
    },
    handleScroll(e) {
      this.$nextTick(function () {
        if (
          this.$refs.tableBox &&
          this.$refs.tableBox.getBoundingClientRect().top < 128
        ) {
          // this.tableHeight = this.$refs.mainCon.getBoundingClientRect().height - 84
          this.tableHeight = window.innerHeight - 218

          if (document.getElementsByClassName('tableBoxCur').length) {
            document.getElementsByClassName('tableBoxCur')[0].style.height =
              null
          }
          this.hiddleToolBar = true
        } else {
          this.hiddleToolBar = false
        }
      })
    },
    getApi() {
      if (localStorage.getItem('judgeRoleCode') === 'company') {
        this.api = 'api-s/report/export_JC_NC_IPQC_TYPE'
      } else {
        this.api = 'api-s/report/export_JC_CS_IPQC_TYPE'
      }
    },
  },
  mounted() {
    window.addEventListener('scroll', this.handleScroll, true)
    let that = this
    this.$nextTick(function () {
      let tableHeightCur = this.$refs.tableBox1.$el.clientHeight
      let tableTop = this.$refs.tableBox.getBoundingClientRect().top
      if (tableHeightCur + tableTop > window.innerHeight) {
        this.tableHeight =
          this.$refs.mainCon.getBoundingClientRect().height - 86
      } else {
        document.getElementsByClassName('tableBoxCur').length &&
          (document.getElementsByClassName('tableBoxCur')[0].style.height =
            window.innerHeight - tableTop - 28 + 'px')
      }

      window.onresize = function () {
        if (!that.$refs.tableBox1) {
          return
        }
        let tableHeightCur = that.$refs.tableBox1.$el.clientHeight
        let tableTop = that.$refs.tableBox.getBoundingClientRect().top
        if (tableHeightCur + tableTop > window.innerHeight) {
          that.tableHeight =
            that.$refs.mainCon.getBoundingClientRect().height - 86
        } else {
          document.getElementsByClassName('tableBoxCur').length &&
            (document.getElementsByClassName('tableBoxCur')[0].style.height =
              window.innerHeight - tableTop - 40 + 'px')
        }
      }
    })
  },
}
</script>

<style lang="less" scoped>
/deep/ .el-form-item__label {
  font-size: 14px;
  color: #333333;
}
.mainCon {
  padding-top: 0;
  padding-bottom: 0;
}
@import '../../../static/css/filterArea.less';
.mainCon {
  padding-top: 0;
  padding-bottom: 0;
}
</style>
